package cn.fayang.org.service.impl;

import cn.fayang.basic.service.impl.BaseServiceImpl;
import cn.fayang.org.domain.Department;
import cn.fayang.org.mapper.DepartmentMapper;
import cn.fayang.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * service接口实现类
 */
@Service
//只读
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    //注入service
    @Autowired
    private DepartmentMapper departmentMapper;



    /**
     * 层级关系无限极树
     * @return
     */
    @Override
    public List<Department> querTree(){
        List<Department> departments = departmentMapper.loadAll();
        HashMap<Long, Department> allDept = new HashMap<>();
        for (Department department : departments) {
            allDept.put(department.getId(),department);
        }
        List<Department> fistDept = new ArrayList<>();
        for (Department tmp : departments) {
            if(tmp.getParent_id() == null){
                fistDept.add(tmp);
            }else {
                Department parent = allDept.get(tmp.getParent_id());
                if(parent != null){
                    parent.getChildren().add(tmp);
                }
            }
        }
        return fistDept;
    }

}
